import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wk_robot2/app/models/WifiInfo.dart';

import '../../../blt/RobotCommandsHelper.dart';
import '../../../blt/protobuf/BleBindOrSwitchWifi.pb.dart';
import '../../../const/AppConst.dart';
import '../../../event/DataCallBack.dart';
import '../../../routes/app_pages.dart';
import '../../../widget/tips.dart';
import '../../bindtip/views/bindtip_view.dart';

class WifiPasswordController extends GetxController {
  var passwordTextEdit = TextEditingController().obs;
  var pwVisible = false.obs;
  var wifiInfoMap = {}.obs;

  var  wifiInfo = WifiInfo().obs;

  @override
  void onInit() {
    super.onInit();
    wifiInfo.value = Get.arguments;
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  void configRoboteWifiPw() {
    if (passwordTextEdit.value.text.trim() == '') {
      Tips.showToast('请输入密码.');
      return;
    }

    wifiInfo.value.setPw(passwordTextEdit.value.text);

    print('开始配置wifi');
    Tips.showLoading();
    RobotCommandsHelper().configWifiList(wifiInfo.value.c!, wifiInfo.value!.s!, wifiInfo.value.getPw(), DataCallBack(
        deviceCallBack: (data) {
          Tips.dismissLoading();
          BindOrSwitchWifiResponse wifiResponse = BindOrSwitchWifiResponse.fromBuffer(data[AppConst.BTL_DATA_KEY] as List<int>);
          print('wifi配置结果, ${wifiResponse.data}');
          Map wifiRepsonse = json.decode(wifiResponse.data);
          if(wifiRepsonse['co'] == 102) { //wifi联网成功.
            print('============> wifi联网成功');
            // 绑定机器人.
            Get.toNamed(Routes.BINDING);

          } else if(wifiRepsonse['co'] == -1) { //联网失败.
             int errorCode = wifiRepsonse['ec'];
             /*if (errorCode == 13) {
               Tips.showToast('Wifi配置失败,WIFI连接不上.');
             } else if (errorCode == 12) {
               Tips.showToast('Wifi配置失败,WIFI不可用.');
             } else if (errorCode == 0) {
               Tips.showToast('Wifi配置失败,WiFi连接失败.');
             } else if (errorCode == 4) {
               Tips.showToast('Wifi配置失败,Wifi连接超时.');
             }  if (errorCode == 0) {
               Tips.showToast('Wifi配置失败,未知错误.');
             }*/
             Get.toNamed(Routes.BINDTIP,arguments: {
               'type': WIFI_UNVAILABLE_ERROR
             });

            // wifi配置结果, {"co":-1,"ec":13} //WIFI连接不上
            // wifi配置结果, {"co":-1,"ec":12} //WIFI不可用.
            // wifi配置结果, {"co":-1,"ec":0} //WiFi连接失败错

          }
        }
    ));




  }

}
